package com.elektronikforumet.camalert;

import java.text.DecimalFormat;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class MainActivity extends Activity {
	
	private static final int GMT1_OFFSET = 1 * 60 * 60 * 1000;
	
	private SpeedsignView mSpeedSign;
	private TextView mTextSpeed; //Current speed textfield
	private TextView mTextLatitude; //Current latitude
	private TextView mTextLongitude; //Current longitude
	private TextView mTextCamDistance; //Distance to camera textfield
	private TextView mTextCamLatitude; //Camera latitude
	private TextView mTextCamLongitude; //Camera longitude
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //Assign controls
        mSpeedSign = (SpeedsignView) findViewById(R.id.speedsign);
        mTextSpeed = (TextView) findViewById(R.id.speed);
        mTextLatitude = (TextView) findViewById(R.id.latitude);
        mTextLongitude = (TextView) findViewById(R.id.longitude);
        mTextCamDistance = (TextView) findViewById(R.id.cam_distance);
        mTextCamLatitude = (TextView) findViewById(R.id.cam_latitude);
        mTextCamLongitude = (TextView) findViewById(R.id.cam_longitude);
       
    	//Start GPS service
        GpsListener.setMainActivity(this);
        Intent svc = new Intent(this, GpsListener.class);
        startService(svc);
}

    @Override
    public void onResume() {
    	super.onResume();
    	
       	//TODO: Handle preferences here
    	//SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    	
    	//boolean booltmp = new Boolean(prefs.getBoolean("imperical", false));
    	//speedsign.setSpeed((booltmp ? 30 : 50));
    }
    
    /**
     * Handling screen rotation manually to avoid running onCreate again. 
     */
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		setContentView(R.layout.main);
	}

	@Override
	protected void onPause() {
		super.onPause();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		//Stop GPS service
        Intent svc = new Intent(this, GpsListener.class);
        stopService(svc);
	}

    public void updateGPS() {
    	DecimalFormat sevenDecimal = new DecimalFormat("#0.0000000");
    	DecimalFormat noDecimal = new DecimalFormat("#0");
    	
		Coordinate coordCurrent = new Coordinate(
				(float)GpsListener.getLocation().getLongitude(), 
				(float)GpsListener.getLocation().getLatitude());
		
		SpeedCamera closestCam = GpsListener.getClosestCam();
		
		mTextSpeed.setTextColor(Color.WHITE);
		mSpeedSign.setDrawEnabled(false);

		//Check if there are any cameras around
		if(closestCam != null) {
			Coordinate closestCamCoord = closestCam.getLocation();
    		
			//Get warning-distance from preferences
			SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
			int iDistAlert = Integer.parseInt(prefs.getString("distance_alert", "500"));

			//Check if we are inside warning-area
			if ((int)GpsListener.getClosestCamDist() <= iDistAlert) {
				mSpeedSign.setDrawEnabled(true);
				
				//If we drive too fast, show speed in red, otherwise green
				if (closestCam.getSpeed() <= (int)(GpsListener.getSpeed()*3.6))
					mTextSpeed.setTextColor(Color.RED);
				else
					mTextSpeed.setTextColor(Color.GREEN);
			}
			
			mTextCamLatitude.setText(sevenDecimal.format(closestCamCoord.getLatitude()));
			mTextCamLongitude.setText(sevenDecimal.format(closestCamCoord.getLongitude()));
			mTextCamDistance.setText(noDecimal.format(closestCamCoord.distanceTo(coordCurrent)));
			mSpeedSign.setSpeed(closestCam.getSpeed());
        }
		else { //No cameras around
			mTextCamLatitude.setText("---");
			mTextCamLongitude.setText("---");
			mTextCamDistance.setText("---");
		}
		
    	//Update widgets
    	mTextSpeed.setText(noDecimal.format(GpsListener.getSpeed()*3.6));
    	mTextLatitude.setText(sevenDecimal.format(GpsListener.getLocation().getLatitude()));
    	mTextLongitude.setText(sevenDecimal.format(GpsListener.getLocation().getLongitude()));
    }
    
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(Menu.NONE, 0, Menu.NONE, this.getString(R.string.menu_preferences));
		menu.add(Menu.NONE, 2, Menu.NONE, this.getString(R.string.menu_databases));
		menu.add(Menu.NONE, 3, Menu.NONE, this.getString(R.string.menu_showmap));
		menu.add(Menu.NONE, 1, Menu.NONE, this.getString(R.string.menu_exit));
		return(super.onCreateOptionsMenu(menu));
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case 0: //Preferences
				startActivity(new Intent(this, EditPreferences.class));
				return(true);
			case 1: //Exit
				Intent svc = new Intent(this, GpsListener.class);
		        stopService(svc);
				finish();
				return(true);
			case 2:
				startActivity(new Intent(this, DatabaseManagerActivity.class));
				return(true);
			case 3:
				startActivity(new Intent(this, GoogleMapActivity.class));
				return(true);
		}
		return(super.onOptionsItemSelected(item));
	}
}